import { DataSource } from 'typeorm';
import { User } from '../entities/User';
import { Post } from '../entities/Post';
import { Payment } from '../entities/Payment';
import { Subscription } from '../entities/Subscription';
import { UserCredit } from '../entities/UserCredit';
import { CreditTransaction } from '../entities/CreditTransaction';
import { Design } from '../entities/Design';

// 验证和读取环境变量
const getEnvVar = (name: string, defaultValue?: string): string => {
  const value = process.env[name] || defaultValue;
  if (!value && !defaultValue) {
    console.warn(`⚠️  环境变量 ${name} 未设置`);
  }
  return value || '';
};

// 数据库配置
const dbConfig = {
  type: 'mysql' as const,
  host: getEnvVar('DB_HOST', 'localhost'),
  port: parseInt(getEnvVar('DB_PORT', '3306')),
  username: getEnvVar('DB_USERNAME', 'root'),
  password: getEnvVar('DB_PASSWORD'),
  database: getEnvVar('DB_NAME', 'express_app'),
  synchronize: process.env.NODE_ENV === 'development',
  logging: false,
  entities: [User, Post, Payment, Subscription, UserCredit, CreditTransaction, Design],
  migrations: ['src/migrations/*.ts'],
  subscribers: ['src/subscribers/*.ts'],
};

// 调试输出数据库配置（隐藏密码）
console.log('🔧 数据库配置:');
console.log(`  主机: ${dbConfig.host}`);
console.log(`  端口: ${dbConfig.port}`);
console.log(`  用户名: ${dbConfig.username}`);
console.log(`  密码: ${dbConfig.password ? '***已设置***' : '❌未设置'}`);
console.log(`  数据库: ${dbConfig.database}`);
console.log(`  环境: ${process.env.NODE_ENV || 'development'}`);

export const AppDataSource = new DataSource(dbConfig);

export const initializeDatabase = async (): Promise<boolean> => {
  try {
    // 在连接前再次验证密码
    if (!dbConfig.password) {
      throw new Error('数据库密码未设置。请检查 DB_PASSWORD 环境变量。');
    }
    
    await AppDataSource.initialize();
    console.log('✅ Database connection established successfully');
    return true;
  } catch (error) {
    console.error('❌ Database connection failed:', error instanceof Error ? error.message : error);
    console.error('❌ 数据库连接配置:');
    console.error(`   - 主机: ${dbConfig.host}:${dbConfig.port}`);
    console.error(`   - 用户: ${dbConfig.username}`);
    console.error(`   - 数据库: ${dbConfig.database}`);
    console.error(`   - 密码状态: ${dbConfig.password ? '已提供' : '未提供'}`);
    console.warn('⚠️  Application will continue without database functionality');
    console.warn('⚠️  Please check your database configuration in .env file');
    return false;
  }
};